package com.samnative.pineapple.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.samnative.pineapple.utils.TimeCount;
import com.samnative.pineapple.value.Config;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.samnative.pineapple.entity.LoginModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.MD5Util;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import ezy.ui.view.RoundButton;


/**
 * 登录 =》验证码登录
 */
public class LoginForCodeActivity extends BaseActivity implements OnClickListener, TimeCount.ITimeCountListener {

    /**
     * 输入手机号
     */
    private EditText etPhone, et_pwd;

    /**
     * 登陆按钮
     */
    private RoundButton btnLogin;
    /**
     * 获取验证码
     */
    private RoundButton tv_get_verity;

    private String mobile, pwd;
    public static LoginForCodeActivity instance = null;

    /**
     * 操作指令
     */
    private int event = -1;

    /**
     * 登录后立马要跳转
     */
    private String openurl;

    /**
     * 是否是H5进来的登录，如果是要原路返回H5
     */
    private boolean webinto;

    /**
     * 定时间器
     */
    private TimeCount mTimeCount;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_for_code;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        findViewById(R.id.close_iv).setOnClickListener(this);
        event = getIntent().getIntExtra("event", -1);
        openurl = getIntent().getStringExtra("openurl");
        webinto = getIntent().getBooleanExtra("webinto", false);

        etPhone = (EditText) findViewById(R.id.et_phone);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        btnLogin = (RoundButton) findViewById(R.id.btn_login);
        findViewById(R.id.tv_register).setOnClickListener(this);
        find(R.id.tv_yzm_login).setOnClickListener(this);
        tv_get_verity = find(R.id.tv_get_verity);
        tv_get_verity.setOnClickListener(this);

//        //设置显示或隐藏密码
//        ((CheckBox) findViewById(R.id.ib_change_pw)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (b) {
//                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//                } else {
//                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                }
//                et_pwd.setSelection(et_pwd.getText().length());
//            }
//        });
        mTimeCount = new TimeCount(60000, 1000);
        mTimeCount.setTimerCountListener(this);

        btnLogin.setOnClickListener(this);
        phoneChange();
        pwdChange();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.close_iv:
                if (event == 1) {
                    startActivity(new Intent()
                            .putExtra("home", true)
                            .setClass(this, MainActivity.class));
                } else {
                    setResult(RESULT_CANCELED);
                    finish();
                }
                break;
            case R.id.find_pwd_tv://找回密码
                startActivity(new Intent()
                        .putExtra("type", 2)
                        .setClass(mContext, PasswordLoginVerityActivity.class));
                break;
            case R.id.btn_login:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                    return;
                }
                if (et_pwd.getText().toString().isEmpty()) {

                    FancyToast.showToast(mContext, "请输入验证码", FancyToast.WARNING, false);
                } else {
                    mobile = etPhone.getText().toString();
                    pwd = et_pwd.getText().toString();

                    doLogin();
                }
                break;
//            case R.id.protocol_tv:
////                startActivity(new Intent(context,
////                        RegistrationProtocolActivity.class));
//                Intent intent = new Intent(context, WebViewActivity.class);
//                intent.putExtra("url", ConstsObject.web_url + "Introduction/index/registDeal");
//                startActivity(intent);
//                break;
            case R.id.tv_register:
                Intent intent1 = new Intent(mContext, RegisterActivity.class);
                startActivity(intent1);
                break;
//            case R.id.iv_clear:
//                etPhone.getText().clear();
//                break;
            case R.id.tv_yzm_login: {
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent, false);
                finish(R.anim.act_web_back1, R.anim.act_web_back2);
            }
            break;
            case R.id.tv_get_verity:
                if (etPhone.getText().toString().isEmpty()) {
                    FancyToast.showToast(mContext, getString(R.string.input_phone), FancyToast.WARNING, false);
                } else {
                    requestCode();
                }

                break;
            default:
                break;
        }
    }


    /**
     * 获取验证码
     */
    private void requestCode() {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", etPhone.getText().toString().trim());
        map.put("devicenumber", Config._uuid);
        map.put("sendType", "login_");
        map.put("privatekey", MD5Util.getMD5Str(etPhone.getText().toString().trim() + Config._API_KEY));
        map.put("_apiname", "user.public.sendvalicode");

        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                // TODO Auto-generated method stub
                mTimeCount.start();
                tv_get_verity.setEnabled(false);
                tv_get_verity.setOnClickListener(null);

                FancyToast.showToast(mContext, getString(R.string.verify_send_success), FancyToast.INFO, false);
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }
        });
    }


    /**
     * 执行登录
     */
    private void doLogin() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "user.login.login");
        map.put("username", mobile);
        map.put("loginpwd", MD5Util.getMD5Str(et_pwd.getText().toString().trim() + Config._API_KEY));
        map.put("devtype", "A");
        map.put("type", "1");
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    LoginModel registerModel = GsonUtils.fromJson(result.toString(), LoginModel.class);
                    AppPrefer.getInstance(mContext).put(AppPrefer.mtoken, registerModel.getData().getMtoken());
//                    PreferencesUtils.putString(context, PreferencesUtils.mobile, registerModel.getData().getMobile());
//                    PreferencesUtils.putString(context, PreferencesUtils.role, registerModel.getData().getRole());
//                    PreferencesUtils.putString(context, PreferencesUtils.type, registerModel.getData().getType());
                    AppPrefer.getInstance(mContext).put(AppPrefer.isPrivacyPolicy, true);
                    showUserInfo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);

            }

        });
    }

    /**
     * 获取用户信息
     */
    public void showUserInfo() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("_apiname", "user.index.main");
            map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken));

            HttpRequest.post(this, "", map, new JsonResult() {
                @Override
                public void reqestSuccess(JSONObject result) {
                    // TODO Auto-generated method stub
                    try {
                        AppPrefer.getInstance(mContext).put(AppPrefer.userinfo, result.toString());
                        if (!webinto) {
                            //正常登录情况
                            if (openurl == null) {
                                //没有什么要跳转的，只去主页就行了
                                Intent intent = new Intent().setClass(mContext, MainActivity.class);
                                intent.putExtra("relogin", true);
                                startActivity(intent);
                            } else {
                                Intent[] intents = new Intent[2];
                                intents[0] = new Intent(mContext, MainActivity.class);
                                intents[0].putExtra("relogin", true);
                                intents[1] = new Intent(mContext, Webview2Activity.class);
                                intents[1].putExtra("url", openurl);
                                startActivities(intents);
                            }
                            finish();
                        } else {
                            //从h5页面过来的情况
                            setResult(201);
                            finish();
                        }


                        if (LoginForCodeActivity.instance != null) {
                            LoginForCodeActivity.instance.finish();
                        }

                        if (RegisterActivity.instance != null) {
                            RegisterActivity.instance.finish();
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (LoginForCodeActivity.this.event == 1) {
                startActivity(new Intent()
                        .putExtra("home", true)
                        .setClass(this, MainActivity.class));
            } else {
                setResult(RESULT_CANCELED);
                finish();
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPageEnd("登陆");
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onPageStart("登陆");
//        MobclickAgent.onResume(this);
    }

    @Override
    public void onStart() {
        super.onStart();
//        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(MessageEvent event) {
//        this.event = event.getEvent();
//    }

    //-------------------------------------监听开始---------------------------------------------

    /**
     * 手机输入框监听
     */
    private void phoneChange() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mobile = etPhone.getText().toString();
                if (mobile.length() < 6 || et_pwd.length() < 6) {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector3));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_gray_bg));
//                    btnLogin.setClickable(false);
                } else {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_white));
//                    btnLogin.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 密码监听
     */
    private void pwdChange() {
        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mobile = etPhone.getText().toString();
                pwd = et_pwd.getText().toString();
//                if (mobile.length() < 6 || pwd.length() < 6) {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector3));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_gray_bg));
////                    btnLogin.setClickable(false);
//                } else {
//                    btnLogin.setBackground(getResources().getDrawable(
//                            R.drawable.login_btn_selector));
//                    btnLogin.setTextColor(getResources().getColor(R.color.main_white));
////                    btnLogin.setClickable(true);
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //====================================================================

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
//        tv_get_verity.setBackgroundDrawable((getResources()
//                .getDrawable(R.drawable.btn_verify_selector_gray)));
        tv_get_verity.setText((millisUntilFinished / 1000) + getString(R.string.verify_confirm));
        tv_get_verity.setEnabled(false);
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
//        tv_get_verity.setBackgroundDrawable((getResources()
//                .getDrawable(R.drawable.btn_verify_selector_red)));
        tv_get_verity.setText(getString(R.string.verify_send_again));
        tv_get_verity.setEnabled(true);
        tv_get_verity.setOnClickListener(this);
    }
}
